package com.geese.module.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.geese.common.constants.BusinessConstants;
import com.geese.common.constants.Constants;
import com.geese.common.entity.Business;
import com.geese.common.entity.Order;
import com.geese.common.entity.TransferRecordDO;
import com.geese.common.util.DateUtil;
import com.geese.common.vo.Page;
import com.geese.exception.BusinessException;
import com.geese.module.admin.vo.OrderVO;
import com.geese.module.business.dao.BusinessMapper;
import com.geese.module.business.dao.TransferRecordMapper;
import com.geese.module.business.service.ITransferRecordService;
import com.geese.module.business.vo.TransferRecordVO;
import com.geese.module.ceo.dao.OrderMapper;
import com.geese.module.user.model.SecurityUser;
import com.geese.module.wechat.vo.ShopkeeperOrderVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by huweiwei on 2017/3/27.
 */
@Service
public class TransferRecordServiceImpl implements ITransferRecordService {

    private static final Logger logger = Logger.getLogger(TransferRecordServiceImpl.class);
    @Autowired
    private TransferRecordMapper transferRecordMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Map<String, Object> selectList(Page page, TransferRecordVO transferRecordVO) {
        PageHelper.startPage(page.getCurrPage(), page.getPageSize(), " id desc");
        List<TransferRecordDO> list = transferRecordMapper.selectList(transferRecordVO);
        PageInfo pages = new PageInfo(list);
        Map<String, Object> pageInfo = Maps.newHashMap();
        pageInfo.put(Constants.CURR_PAGE, pages.getPageNum());
        pageInfo.put(Constants.TOTAL_PAGE, pages.getPages());
        pageInfo.put(Constants.TOTAL, pages.getTotal());
        Map<String, Object> result = Maps.newHashMap();
        result.put(Constants.PAGE_INFO, pageInfo);
        result.put("transferList", list);
        return result;
    }

    @Override
    public void doPay(SecurityUser user, TransferRecordDO transferRecordDO) {
        String json = user.getExtra();
        Business business = JSON.parseObject(json, Business.class);
        if (business == null) {
            throw new BusinessException(120069);
        }
        TransferRecordDO check = transferRecordMapper.findById(transferRecordDO.getId());
        if (check.getStatus() != 0) {
            throw new BusinessException(120104);
        }
        if (!Objects.equals(check.getBusinessId(), business.getId())) {
            throw new BusinessException(120108);
        }
        check.setPhotoUrl(transferRecordDO.getPhotoUrl());
        check.setStatus(BusinessConstants.TRANSFER_RECORD_STATUS_PAY);
        int skip = transferRecordMapper.updateRecord(check);
        if (skip != 1) {
            throw new BusinessException(120034);
        }
    }

    @Override
    public Map<String, Object> getIndex(SecurityUser user) {
        String json = user.getExtra();
        Business business = JSON.parseObject(json, Business.class);
        if (business == null) {
            throw new BusinessException(120069);
        }
        List<TransferRecordDO> list = transferRecordMapper.selectListByBusinessId(business.getId());
        List<Map<String, Object>> logList = Lists.newArrayList();
        double total = 0d;
        double pay = 0d;
        if (CollectionUtils.isNotEmpty(list)) {
            for (TransferRecordDO transferRecordDO : list) {
                int status = transferRecordDO.getStatus();
                double amount = transferRecordDO.getTransferAmount();
                total += amount;
                if (status == 2) {
                    pay+= amount;
                }

                Map<String, Object> temp = Maps.newHashMap();
                temp.put("startTime", transferRecordDO.getStartTime());
                temp.put("endTime", transferRecordDO.getEndTime());
                temp.put("amount", amount);
                temp.put("status", status);
                logList.add(temp);
            }

        }
        Map<String, Object> result = Maps.newHashMap();
        result.put("logList", logList);
        result.put("total", total);
        result.put("pay", pay);
        result.put("noPay", total - pay);
        return result;
    }


    @Override
    public void generateTransferRecord() {
        List<Business> businessList = businessMapper.findAllActive();
        for (Business business : businessList) {
            int settleCycle = business.getSettleCycle();
            Date endTime = DateUtil.truncate(new Date(), Calendar.DATE);
            Date startTime = DateUtil.addDays(endTime, 0 - settleCycle);
            String auditTime = DateUtil.format(business.getAuditTime(), DateUtil.PATTERN_ISO_ON_DATE);
            String now = DateUtil.format(endTime, DateUtil.PATTERN_ISO_ON_DATE);
            long days = DateUtil.countHour(now, auditTime, DateUtil.PATTERN_ISO_ON_DATE) / 24;
            long remainder = days % settleCycle;
            if (remainder == 0) {
                ShopkeeperOrderVO shopkeeperOrderVO = new ShopkeeperOrderVO();
                shopkeeperOrderVO.setShopkeeperId(business.getId());
                shopkeeperOrderVO.setStartDate(startTime);
                shopkeeperOrderVO.setEndDate(endTime);
                List<Integer> status = Lists.newArrayList(1,3);
                List<Order> orders = orderMapper.selectOrderToGenerate(shopkeeperOrderVO, status);
                TransferRecordDO transferRecordDO = new TransferRecordDO();
                // TODO: 2017/3/29 生成单号规则
                Integer transferNumber = RandomUtils.nextInt(1000000000, Integer.MAX_VALUE);
                transferRecordDO.setStatus(BusinessConstants.TRANSFER_RECORD_STATUS_UNPAY);
                transferRecordDO.setTransferNumber(transferNumber);
                transferRecordDO.setBusinessId(business.getId());
                transferRecordDO.setStartTime(startTime);
                transferRecordDO.setEndTime(endTime);
                transferRecordDO.setOrderQuantity(orders.size());
                transferRecordDO.setSingleAmount(business.getSingleAmount());
                transferRecordDO.setTransferInterval(settleCycle);
                transferRecordDO.setTransferAmount(business.getSingleAmount() * orders.size());
                transferRecordMapper.insert(transferRecordDO);
                logger.warn("生成一个账单，单号：" + transferNumber);
            }
        }
    }
}
